package com.rural.bus.driver.receiver;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rural.bus.driver.LoginActivity;
import com.rural.bus.driver.MainActivity;
import com.rural.bus.driver.MyApplication;
import com.rural.bus.driver.R;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.fragment.MyOrderFragment;
import com.rural.bus.driver.model.Order;
import com.rural.bus.driver.utils.ActivityControl;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	
	private Context context;
	private static final String TAG = "JPush";
	private MediaPlayer  player;

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		// Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() +
		// ", extras: " + printBundle(bundle));
		this.context = context;
		if(player == null){
			player = MediaPlayer.create(context, R.raw.sound_new_order);
		}

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
			// send the Registration Id to your server...

		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			processMessage(context, bundle);

		}

		// else if
		// (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction()))
		// {
		// Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
		// int notifactionId =
		// bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
		// Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
		// processMessage(context, bundle);
		//
		// }
		// else if
		// (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction()))
		// {
		// Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
		//
		// //打开自定义的Activity
		// // Intent i = new Intent(context, TestActivity.class);
		// // i.putExtras(bundle);
		// // //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
		// Intent.FLAG_ACTIVITY_CLEAR_TOP );
		// // context.startActivity(i);
		//
		// }
		// else if
		// (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction()))
		// {
		// Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " +
		// bundle.getString(JPushInterface.EXTRA_EXTRA));
		// //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
		//
		// }
		// else
		// if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction()))
		// {
		// // boolean connected =
		// intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE,
		// false);
		// // Log.w(TAG, "[MyReceiver]" + intent.getAction()
		// +" connected state change to "+connected);
		// } else {
		// // Log.d(TAG, "[MyReceiver] Unhandled intent - " +
		// intent.getAction());
		// }
	}

	private void processMessage(Context context, Bundle bundle) {
		// {"action":0,"expireTime":300,"message":"您有新订单快来抢吧!","order":{"carType":0,"distance":10000,"endLatitude":40.200851,"endLocation":"企业墅","endLongtitude":116.295158,"estimatePrice":22000,"number":1,"orderId":157,"orderStatus":0,"orderType":0,"perDistance":2.2,"startLatitude":40.200851,"startLocation":"张各庄","startLongtitude":116.295158,"takeTime":1450883400000,"userId":1,"userName":"张三","userPhone":"13333333333"}}
		// {"action":4,"expireTime":300,"message":"乘客取消订单了!","order":{"carType":0,"createTime":1449628453000,"distance":10000,"driverId":1,"driverName":"陈馨(宝马湘A**897)","driverPhone":"13333333331","endLatitude":40.047862,"endLocation":"北领地c区","endLongtitude":116.363094,"estimatePrice":15000,"groupId":8881611,"number":1,"orderId":125,"orderStatus":4,"orderType":1,"perDistance":1.5,"remarks":"","startLatitude":40.089919,"startLocation":"专家国际公馆","startLongtitude":116.324178,"takeTime":9180000,"userId":4,"userName":"马杰","userPhone":"13112345678"}}
		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
		// String str=bundle.getString(JPushInterface.EXTRA_ALERT);
		Log.d(TAG, "--------------start----------------");
		Log.d(TAG, message);
		Log.d(TAG, "--------------end----------------");
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(message);

			switch (jsonObject.optInt("action")) {
			case 0:
				// 新订单
				Toast.makeText(MyApplication.instance(), "有新订单", Toast.LENGTH_SHORT).show();
				Order order = new Gson().fromJson(jsonObject.getString(("order")), new TypeToken<Order>() {
				}.getType());
				
				if(player == null){
					player = MediaPlayer.create(context, R.raw.sound_new_order);
				}
				player.start();

				Intent intent = new Intent(context, MainActivity.class);
				order.expireTime = jsonObject.optInt("expireTime", 300);
				intent.putExtra("order", order);
				intent.putExtra("tag", "new_order");
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
				
				
				break;
			case 4:
				// 乘客取消了订单
				Toast.makeText(MyApplication.instance(), "有乘客取消订单", Toast.LENGTH_SHORT).show();
				
				Order order2 = new Gson().fromJson(jsonObject.getString(("order")), new TypeToken<Order>() {
				}.getType());

				Intent intent2 = new Intent(context, MainActivity.class);
				order2.expireTime = jsonObject.optInt("expireTime", 300);
				intent2.putExtra("order", order2);
				intent2.putExtra("tag", "cancel_order");
				intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				MyOrderFragment.isFresh = true;
				context.startActivity(intent2);
				break;
			case 6:
				Toast.makeText(MyApplication.instance(), "乘客使用余额支付成功", Toast.LENGTH_SHORT).show();
				
				Order order3 = new Gson().fromJson(jsonObject.getString(("order")), new TypeToken<Order>() {
				}.getType());

				Intent intent3 = new Intent(context, MainActivity.class);
				intent3.putExtra("order", order3);
				intent3.putExtra("tag", "balance_charge");
				intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				MyOrderFragment.isFresh = true;
				context.startActivity(intent3);
				//ToastUtil.showToast("余额支付：" + jsonObject.getString(("order")));
				MyOrderFragment.isFresh = true;
				break;
			case 7:
				Toast.makeText(MyApplication.instance(), "乘客使用现金支付成功", Toast.LENGTH_SHORT).show();
				
				Order order4 = new Gson().fromJson(jsonObject.getString(("order")), new TypeToken<Order>() {
				}.getType());
				
				// {"order":{"endLatitude":40.210416,"createTime":1453620936000,"remarks":"","finalPrice":0.3,"carType":0,"endLongtitude":116.29907,"distance":20,"endLocation":"南邵中学","userId":4,"driverId":1,"userName":"马杰","userPhone":"13112345678","startLongtitude":116.29907,"driverName":"陈陈2(宝马湘A**897)","orderId":280,"startLatitude":40.210417,"orderType":0,"takeTime":1453620840000,"startLocation":"世界城2","perDistance":1.7,"number":1,"driverPhone":"13522761340","orderStatus":6,"groupId":9572551,"payStatus":0,"estimatePrice":2},"message":"乘客选择现金支付","expireTime":300,"action":7}
				Intent intent4 = new Intent(context, MainActivity.class);
				intent4.putExtra("order", order4);
				intent4.putExtra("tag", "cash_charge");
				intent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				MyOrderFragment.isFresh = true;
				context.startActivity(intent4);
				
				
			//	ToastUtil.showToast("现金支付：" + jsonObject.getString(("order")));
				
				MyOrderFragment.isFresh = true;
				break;
			case 8:  //有半个小时内的订单
				Intent intent8 = new Intent(context, MainActivity.class);
				intent8.putExtra("tag", "new_half_hour_order");
				intent8.putExtra("msg", jsonObject.optString("message","有半个小时内出发的订单"));
				intent8.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				MyOrderFragment.isFresh = true;
				context.startActivity(intent8);
				
				break;
			case 10:  //其他设备登录了我的账号
				MyApplication.driverInfo = null;
				MyPreferenceManager.instance().clearPreferences();
				Intent intent10=new Intent(context, LoginActivity.class);
				intent10.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent10);
				Toast.makeText(context, "账号在其他设备上登录，请重新登录", Toast.LENGTH_SHORT).show();
				
//				ActivityControl control = ActivityControl.getInstance();
//				Activity currentActivity = control.getCurrentActivity();
//				while (currentActivity !=null) {
//					control.removeActivity(currentActivity);
//					currentActivity.finish();
//					currentActivity = control.getCurrentActivity();
//				}
				break;
			default:
				break;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
